const URL_PREFIX = "http://www.pudge.wang:3080/api";

const http = {
  get(url, params) {
    if (params) {
      // parmas  {a:3,b:4}   -> ?a=3&b=4
      let arr = [];
      for (const key in params) {
        arr.push(key + "=" + params[key]);
        // arr: ["a=3", "b=4"]
      }
      let str = arr.join("&");
      // str: "a=3&b=4"
      url += "?" + str;
      // url: url?a=3&b=4
    }

    // fetch的get请求没有第二个参数，只能在url后面做拼接
    return fetch(URL_PREFIX + url)
      .then((response) => response.json())
      .then((res) => {
        return res;
      });
  },
  post(url, data) {
    return fetch(URL_PREFIX + url, {
      body: JSON.stringify(data),
      headers: {
        "content-type": "application/json",
      },
      method: "POST",
    })
      .then((response) => response.json())
      .then((res) => {
        return res;
      });
  },
};

export default http;
